package com.csot.ry.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.PageUtil;
import com.csot.ry.domain.TCheckSegment;
import com.csot.ry.domain.TTotalSegment;
import com.csot.ry.poi.ExcelUtilSub;
import com.csot.ry.service.ITCheckSegmentService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.csot.common.annotation.Log;
import com.csot.common.constant.HttpStatus;
import com.csot.common.core.controller.BaseController;
import com.csot.common.core.domain.AjaxResult;
import com.csot.common.core.page.TableDataInfo;
import com.csot.common.enums.BusinessType;
import com.csot.common.utils.ServletUtils;
import com.csot.common.utils.poi.ExcelUtil;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 数据稽核Controller
 * 
 * @author 刘沙
 * @date 2022-06-02
 */
@RestController
@RequestMapping("/ipmanagement/checksegment")
public class TCheckSegmentController extends BaseController {
	@Autowired
	private ITCheckSegmentService tCheckSegmentService;

	/**
	 * 查询数据稽核列表
	 */
	@SuppressWarnings("unchecked")
	@PreAuthorize("@ss.hasPermi('ipmanagement:checksegment:list')")
	@GetMapping("/list/{type}/**")
	public TableDataInfo list(TCheckSegment tCheckSegment,@PathVariable("type") String type) {
		startPage();
		Object obj = ServletUtils.getSession().getAttribute("checksegment");
		List<TCheckSegment> list = new ArrayList<>();
		if (Objects.nonNull(obj)) {
			list = (List<TCheckSegment>) obj;
		}
		list = list.stream().filter(f -> {
			if (type.toLowerCase().equals(f.getIpType()))
				return true;
			return false;
		}).collect(Collectors.toList());
		return getDataTable(list);
	}

	/**
	 * 导出数据稽核列表
	 */
	@PreAuthorize("@ss.hasPermi('ipmanagement:checksegment:export')")
	@Log(title = "数据稽核", businessType = BusinessType.EXPORT)
	@PostMapping("/export/{type}/**")
	public void export(HttpServletResponse response, TCheckSegment tCheckSegment,@PathVariable("type") String type) {

		List<TCheckSegment> list = new ArrayList<>();
		Object obj = ServletUtils.getSession().getAttribute("checksegment");
		if (Objects.nonNull(obj)) {
			list = (List<TCheckSegment>) obj;
		}
		list = list.stream().filter(f -> {
			if (type.toLowerCase().equals(f.getIpType()))
				return true;
			return false;
		}).collect(Collectors.toList());
		ExcelUtil<TCheckSegment> util = new ExcelUtil<TCheckSegment>(TCheckSegment.class);
		util.exportExcel(response, list, "数据稽核数据");
	}

	/**
	 * 获取数据稽核详细信息
	 */
	@PreAuthorize("@ss.hasPermi('ipmanagement:checksegment:query')")
	@GetMapping(value = "/{id}")
	public AjaxResult getInfo(@PathVariable("id") Long id) {
		return AjaxResult.success(tCheckSegmentService.selectTCheckSegmentById(id));
	}

	/**
	 * 新增数据稽核
	 */
	@PreAuthorize("@ss.hasPermi('ipmanagement:checksegment:add')")
	@Log(title = "数据稽核", businessType = BusinessType.INSERT)
	@PostMapping
	public AjaxResult add(@RequestBody TCheckSegment tCheckSegment) {
		return toAjax(tCheckSegmentService.insertTCheckSegment(tCheckSegment));
	}

	/**
	 * 修改数据稽核
	 */
	@PreAuthorize("@ss.hasPermi('ipmanagement:checksegment:edit')")
	@Log(title = "数据稽核", businessType = BusinessType.UPDATE)
	@PutMapping
	public AjaxResult edit(@RequestBody TCheckSegment tCheckSegment) {
		return toAjax(tCheckSegmentService.updateTCheckSegment(tCheckSegment));
	}

	/**
	 * 删除数据稽核
	 */
	@PreAuthorize("@ss.hasPermi('ipmanagement:checksegment:remove')")
	@Log(title = "数据稽核", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
	public AjaxResult remove(@PathVariable Long[] ids) {
		return toAjax(tCheckSegmentService.deleteTCheckSegmentByIds(ids));
	}

	@Log(title = "导入细粒度并稽核", businessType = BusinessType.IMPORT)
	@PreAuthorize("@ss.hasPermi('ipmanagement:checksegment:import')")
	@PostMapping("/importData/{type}/**")
	public AjaxResult importData(MultipartFile file, boolean updateSupport,@PathVariable("type") String type) throws Exception {
		ExcelUtilSub<TCheckSegment> util = new ExcelUtilSub<TCheckSegment>(TCheckSegment.class);
		List<TCheckSegment> tCheckSegmentList = util.importExcel(file.getInputStream());
		for(TCheckSegment tCheckSegment : tCheckSegmentList){
			tCheckSegment.setIpType(type.toLowerCase());
		}
		List<TCheckSegment> list = tCheckSegmentService.importCheckSegment(tCheckSegmentList);
		ServletUtils.getSession().setAttribute("checksegment", list);
		return AjaxResult.success("稽核结束");
	}

	@Log(title = "导入粗粒度并稽核", businessType = BusinessType.IMPORT)
	@PreAuthorize("@ss.hasPermi('ipmanagement:coarsechecksegment:import')")
	@PostMapping("/importDataCoarse/{type}/**")
	public AjaxResult importDataCoarse(MultipartFile file, boolean updateSupport,@PathVariable("type") String type) throws Exception {
		ExcelUtilSub<TCheckSegment> util = new ExcelUtilSub<TCheckSegment>(TCheckSegment.class);
		List<TCheckSegment> tCheckSegmentList = util.importExcel(file.getInputStream());
		for(TCheckSegment tCheckSegment : tCheckSegmentList){
			tCheckSegment.setIpType(type.toLowerCase());
		}
		List<TCheckSegment> list = tCheckSegmentService.importCheckSegmentCoarse(tCheckSegmentList);
		ServletUtils.getSession().setAttribute("checksegment", list);
		return AjaxResult.success("稽核结束");
	}

	@PostMapping("/importTemplate")
	public void importTemplate(HttpServletResponse response) {
		response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
		response.setCharacterEncoding("utf-8");
		try {
			String path = System.getProperty("user.dir");
			path = path + File.separator + "Template" + File.separator + "citysegmentmodel.xlsx";
			IOUtils.write(Files.readAllBytes(Paths.get(path)), response.getOutputStream());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			logger.error("下载ip段模块异常", e);
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	protected TableDataInfo getDataTable(List<?> list) {
		PageUtil.setFirstPageNo(1);
		TableDataInfo rspData = new TableDataInfo();
		rspData.setCode(HttpStatus.SUCCESS);
		rspData.setMsg("查询成功");
		Page<Object> page = PageHelper.getLocalPage();
		int[] ps = PageUtil.transToStartEnd(page.getPageNum(), page.getPageSize());
		if (CollUtil.isEmpty(list)) {
			rspData.setRows(list);
			rspData.setTotal(new PageInfo(new ArrayList<>()).getTotal());
		} else {
			rspData.setRows(CollUtil.sub(list, ps[0], ps[1]));
			rspData.setTotal(list.size());
		}

		return rspData;
	}
}
